package lv.solcraft.replication.server.api;

import java.util.ArrayList;
import java.util.List;

import lv.solcraft.replication.server.boot.ServerConfig;
import lv.solcraft.replication.server.model.Oper;
import lv.solcraft.replication.server.model.OperStateUpdate;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("serverFacade")
public class DefaultServerFacade implements ServerFacade {

    @Autowired
    SaveOpersCommand saveOpersCommand;

    @Autowired
    NewOpersCommand newOpersCommand;

    @Autowired
    UpdateOperStatesCommand updateOperStatesCommand;

    @Autowired
    ServerConfig serverConfig;

    public void save(final List<Oper> opers) {
        saveOpersCommand.save(opers, serverConfig.getSitesList());
    }

    public List<Oper> getFirstNewOpers(long siteId) {
        return newOpersCommand.getOpers(siteId, serverConfig.getOpersBatchSize());
    }

    public void updateStates(List<OperStateUpdate> operStates) {
        updateOperStatesCommand.updateStates(operStates);
    }

    public void saveJSON(long siteId, JSONArray array) {
        List<Oper> opers = new ArrayList<Oper>(array.size());
        for (Object object : array) {
            JSONObject json = (JSONObject) object;
            Oper oper = Oper.fromJSON(siteId, json);
            opers.add(oper);
        }
        save(opers);
    }

    public void updateStatesJSON(long siteId, JSONArray array) {
        List<OperStateUpdate> operStates = new ArrayList<OperStateUpdate>(array.size());
        for (Object object : array) {
            JSONObject json = (JSONObject) object;
            OperStateUpdate operState = OperStateUpdate.fromJSON(siteId, json);
            operStates.add(operState);
        }
        updateStates(operStates);
    }

    public JSONArray getFirstNewOpersJSON(long siteId) {
        JSONArray jsonArray = new JSONArray();
        List<Oper> opers = getFirstNewOpers(siteId);
        for (Oper oper : opers) {
            jsonArray.add(oper.toJSON(true));
        }
        return jsonArray;
    }
}
